package com.sunxd.zstudy.juc;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author: 读写锁
 * 共享锁
 * 排他锁
 *
 * 同样的操作，
 * @date: 2021-03-31 21:26
 **/
public class T12_ReadWriteLock {
     static int value = 1;
     static Lock lock = new ReentrantLock();
     static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
     static  Lock readLock = readWriteLock.readLock();
     static  Lock writeLock = readWriteLock.writeLock();

     public static void read(Lock lock){
         lock.lock();
         try {
             Thread.sleep(1000);
             System.out.println("read over");
         } catch (Exception e) {
             e.printStackTrace();
         } finally {
             lock.unlock();
         }
     }
     public static void write(Lock lock,int v){
         lock.lock();
         try {
             Thread.sleep(1000);
             value = v;
             System.out.println("write over");
         } catch (Exception e) {
             e.printStackTrace();
         } finally {
             lock.unlock();
         }
     }
    public static void main(String[] args) {
         List<Thread> list = new ArrayList<>();

         // 共享锁-竞争
//        for (int i = 0; i < 20; i++) {
//            list.add(new Thread(() ->{
//                    read(lock);
//            }));
//            list.add(new Thread(() ->{
//                write(lock,new Random().nextInt());
//            }));
//        }

        // 读写锁测试
        for (int i = 0; i < 20; i++) {
            list.add(new Thread(() ->{
                read(readLock);
            }));
            if(i % 10 == 0){
                list.add(new Thread(() ->{
                    write(writeLock,new Random().nextInt());
                }));
            }

        }
         list.forEach(x ->x.start());
    }

}
